﻿namespace SimpleAdmin.Web.Core;

using Furion.FriendlyException;

using Microsoft.AspNetCore.Mvc;

using Senparc.Weixin;
using Senparc.Weixin.WxOpen.AdvancedAPIs.Sns;
using Senparc.Weixin.WxOpen.Containers;

/// <summary>
/// 微信小程序接口控制器
/// </summary>
[ApiDescriptionSettings("Application", Tag = "微信小程序接口")]
[Route("/biz/wxopen")]
public class BizWxOpenController : IDynamicApiController
{
    public static readonly string Token = Config.SenparcWeixinSetting.WxOpenToken;//与微信小程序后台的Token设置保持一致，区分大小写。
    public static readonly string EncodingAESKey = Config.SenparcWeixinSetting.WxOpenEncodingAESKey;//与微信小程序后台的EncodingAESKey设置保持一致，区分大小写。
    public static readonly string WxOpenAppId = Config.SenparcWeixinSetting.WxOpenAppId;//与微信小程序后台的AppId设置保持一致，区分大小写。
    public static readonly string WxOpenAppSecret = Config.SenparcWeixinSetting.WxOpenAppSecret;//与微信小程序账号后台的AppId设置保持一致，区分大小写。

    private readonly IAuthService _authService;
    private readonly ISysUserService _sysUserService;

    public BizWxOpenController(IAuthService authService, ISysUserService sysUserService)
    {
        _authService = authService;
        _sysUserService = sysUserService;
    }

    #region Get请求
    [HttpGet]
    [AllowAnonymous]
    public dynamic Now()
    {
        return new { Time = DateTime.Now };
    }
    #endregion

    #region Post请求
    /// <summary>
    /// wx.login登陆成功之后发送的请求
    /// </summary>
    /// <param name="code">微信小程序wx.login()获取的临时code</param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    public async Task<dynamic> OnLogin(string code)
    {
        try
        {
            var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code);
            if (jsonResult.errcode == ReturnCode.请求成功)
            {
                //Session["WxOpenUser"] = jsonResult;//使用Session保存登陆信息（不推荐）
                //使用SessionContainer管理登录信息（推荐）
                var unionId = "";
                var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId);

                var loginResult = await _authService.LoginByWxOpenId(jsonResult.openid, LoginClientTypeEnum.MiniApp);
                loginResult.WxOpenSessionId = jsonResult.session_key;

                return loginResult;
            }
            else
            {
                throw Oops.Bah("微信服务器登录失败");
            }
        }
        catch (global::System.Exception ex)
        {
            throw Oops.Bah($"登录失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 修改昵称或头像，为空则不修改对应项
    /// </summary>
    /// <param name="input">修改后的昵称或头像参数结构</param>
    /// <returns></returns>
    [HttpPost]
    public async Task ModifyNameAndAvatar([FromBody]UserEditNameAvatarInput input)
    {
        var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
        await _sysUserService.ModifyNameAndAvatar(long.Parse(userId!), input.Name, input.Avatar);
    }



    #endregion
}